package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.DeviceMapper;
import com.indusfo.spc.mapper.ScrapWorkMapper;
import com.indusfo.spc.pojo.ScrapWork;
import com.indusfo.spc.service.ScrapWorkService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ScrapWorkServiceImpl implements ScrapWorkService {

    private  static  final Logger logger = LoggerFactory.getLogger(ScrapWorkServiceImpl.class);
    
    @Resource
    private ScrapWorkMapper scrapWorkMapper;

    @Resource
    private DeviceMapper deviceMapper;

    /**
     * 查询
     * @param scrapWork
     * @return
     */
    @Override
    public JSONObject selectScrapWork(ScrapWork scrapWork,String startDate,String endDate) {
        List<ScrapWork> scrapWorkList = null;
        int count = 0;
        try {
            Integer pagesize = scrapWork.getPagesize();
            Integer pageindex = scrapWork.getPageindex();
            if(pagesize != null && pageindex != null) {
                scrapWork.setIncept(pagesize*(pageindex - 1));
            }
            scrapWorkList = scrapWorkMapper.selectScrapWork(scrapWork,startDate,endDate);
            //查询分页总记录数
            count = scrapWorkMapper.countScrapWork(scrapWork,startDate,endDate); //返回查询到的总记录数
            if (scrapWorkList.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据", scrapWorkList, count);
            }
            return JSONObject.oK("查询成功", scrapWorkList, count);
        } catch (
                GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 新增
     * @param scrapWork
     * @return
     */
    @Override
    public JSONObject insertScrapWork(ScrapWork scrapWork) {
        try {
            if(scrapWork.getScrapWorkId()!= null) {
                throw new ParamsErrorException("新增时，不能填写id");
            }
            checkParam(scrapWork);
            // 调用存储过程
            int row = scrapWorkMapper.insertSelective(scrapWork);
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 修改
     * @param scrapWork
     * @return
     */
    @Override
    public JSONObject updateScrapWork(ScrapWork scrapWork) {
        try {
            if(scrapWork.getScrapWorkId()== null) {
                throw new ParamsErrorException("请选择要编辑的报废作业");
            }
            checkParam(scrapWork);
            // 调用存储过程
            int row = scrapWorkMapper.updateByPrimaryKeySelective(scrapWork);
            if(row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 停用/启用/删除
     * @param scrapWorkIds
     * @param dataState
     * @return
     */
    @Override
    public JSONObject definedScrapWork(Long[] scrapWorkIds,Integer[] auditStates , Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (scrapWorkIds == null) {
                throw new ParamsErrorException("报废作业id不能为空");
            }
            for(Integer i: auditStates){
                if(i == 2){
                    throw new ParamsErrorException("已审核的无法删除");
                }
            }
            // 执行存储过程
            int row = scrapWorkMapper.definedScrapWork(scrapWorkIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 审核/反审核
     * @param scrapWorkIds
     * @param auditStates
     * @param auditState
     * @param auditUserId
     * @return
     */
    @Transactional
    @Override
    public JSONObject auditScrapWork(Long[] scrapWorkIds, Integer[] auditStates, Integer auditState, Integer auditUserId) {
        if(auditState == null) {
            throw new ParamsErrorException("审核状态不能为空");
        }else if(auditState != 1 && auditState != 2 ) {
            throw new ParamsErrorException("审核状态错误");
        }
        if (scrapWorkIds == null || scrapWorkIds.length == 0) {
            throw new ParamsErrorException("ID不能为空");
        }
        if (auditStates == null || auditStates.length == 0) {
            throw new ParamsErrorException("审核状态数组不能为空");
        }
        for(Integer i : auditStates){
            if(auditState == 1){
                if(i == auditState){
                    throw new ParamsErrorException("未审核的不能反审核");
                }
            }else {
                if(i == auditState){
                    throw new ParamsErrorException("已审核的不能审核");
                }
            }
        }
        // 执行存储过程
        List<Integer> deviceIds = scrapWorkMapper.selectByScrapWorkId(scrapWorkIds);
        if(deviceIds.size() != scrapWorkIds.length){
            throw new ParamsErrorException("已报废的设备不能再次报废");
        }
        int row = scrapWorkMapper.auditScrapWork(scrapWorkIds, auditState, auditUserId);
        int rows = deviceMapper.scrapDevice(deviceIds);
        String msg = "";
        if (row == 0) {
            // 判断传入的审核状态参数auditState,返回相应信息
            switch (auditState) {
                case 1:
                    throw new ModifyFailedException("反审核失败");
                case 2:
                    throw new ModifyFailedException("审核失败");
                default:
            }
        } else {
            switch (auditState) {
                case 1:
                    msg = "反审核成功";break;
                case 2:
                    msg = "审核成功";break;
                default:
            }
        }
        return JSONObject.oK(msg);
    }

    /**
     * 参数校验
     */
    private void checkParam(ScrapWork scrapWork) {
        if (scrapWork.getDeviceId() == null) {
            throw new ParamsErrorException("请选择设备");
        }
        if (StringUtils.isEmpty(scrapWork.getScrapWorkNo())) {
            throw new ParamsErrorException("请填写报废作业单号");
        }
        if (scrapWork.getScrapWorkNo().getBytes().length > 50) {
            throw new ParamsErrorException("报废作业单号超过规定,长度50");
        }
        // 单号不能重复
        Integer codeCounts = scrapWorkMapper.queryScrapWorkCode(scrapWork);
        if (codeCounts !=0) {
            throw new ParamsErrorException("该报废作业单号已存在");
        }
    }
    
}
